<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>SFTPGo WebClient - External integration test</title>
</head>

<body>
    <textarea id="textarea_test" name="textarea_test" rows="10" cols="80">The text here will be sent to SFTPGo as blob</textarea>
    <br>
    <button onclick="saveBlob(false);">Save</button>
    <br>
    <button onclick="saveBlob(true);">Save binary file</button>
    <br><br>
    <b>Logs</b>
    <pre id="log"></pre>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        var fileName;
        var sftpgoUser;

        // in real world usage set the origin when you call postMessage, we use `*` for testing purpose here
        $(document).ready(function () {
            if (window.opener == null || window.opener.closed) {
                printLog("window opener gone!");
                return;
            }
            // notify SFTPGo that the page is ready to receive the file
            window.opener.postMessage({type: 'ready'},"*");
        });

        window.addEventListener('message', (event) => {
            if (window.opener == null || window.opener.closed) {
                printLog("window opener gone!");
                return;
            }
            // you should check the origin before continuing
            printLog("new message: "+JSON.stringify(event.data));
            switch (event.data.type){
                case 'readyResponse':
                    // after sending the ready request SFTPGo will reply with this response
                    // now you know the file name and the SFTPGo user
                    fileName = event.data.file_name;
                    sftpgoUser = event.data.user;
                    printLog("ready response received, file name: " + fileName+" SFTPGo user: "+sftpgoUser);
                    // you can initialize your viewer/editor based on the file extension and request the blob
                    window.opener.postMessage({type: 'sendBlob'}, "*");
                    break;
                case 'blobDownloadStart':
                    // SFTPGo may take a while to read the file, just before it starts reading it will send this message.
                    // You can initialize a spinner if required for this file or simply ignore this message
                    printLog("blob download start received, file name: " + fileName+" SFTPGo user: "+sftpgoUser);
                    break;
                case 'blobDownloadError':
                    // SFTPGo was unable to download the file and return it as blob
                    printLog("blob download failed, file name: " + fileName+" SFTPGo user: "+sftpgoUser+" error message: "+event.data.message);
                    break;
                case 'blob':
                    // we received the file as blob
                    var extension = fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
                    printLog("blob received, file name: " + fileName+" extension: "+extension+" SFTPGo user: "+sftpgoUser);
                    if (extension == "txt"){
                        event.data.file.text().then(function(text){
                            $("#textarea_test").val(text);
                        });
                    }
                    break;
                case 'blobSaveResult':
                    // event.data.status is OK or KO, if KO message is not empty
                    printLog("blob save status: "+event.data.status+", message: "+event.data.message);
                    if (event.data.status == "OK"){
                        printLog("blob saved, I'm useless now, close me");
                    }
                    break;
                default:
                    printLog("Unsupported message: " + JSON.stringify(event.data));
            }
        });

        function saveBlob(binary){
            if (window.opener == null || window.opener.closed) {
                printLog("window opener gone!");
                return;
            }
            // if we have modified the file we can send it back to SFTPGo as a blob for saving
            printLog("save blob, binary? "+binary);
            if (binary){
                // we download and save the SFTPGo logo. In a real application check errors
                fetch('https://raw.githubusercontent.com/drakkan/sftpgo/main/docs/howto/img/logo.png')
                    .then(response => response.blob())
                    .then(function(responseBlob){
                        var blob = new File([responseBlob], fileName);
                        window.opener.postMessage({
                            type: 'saveBlob',
                            file: blob
                        },"*");
                    });
            } else {
                var blob = new Blob([$("#textarea_test").val()]);
                window.opener.postMessage({
                    type: 'saveBlob',
                    file: blob
                },"*");
            }
        }

        function printLog(message){
            console.log(message);
            var logger = document.getElementById('log');
            logger.innerHTML += message + '<br>';
        }
    </script>
</body>
